<template>
  <div class="search">
    <van-nav-bar fixed title="商品列表" left-arrow @click-left="$router.go(-1)" />

    <van-search
      readonly
      shape="round"
      background="#ffffff"
      :value= "querySearch || '搜索商品'"
      show-action
      @click="$router.push('/search')"
    >
      <template #action>
        <van-icon @click="showPopup"  class="tool" name="apps-o" />
        <van-popup v-model="show"  position="right" :style="{ width: '60%' , height: '100%' }" ></van-popup>
      </template>
    </van-search>

    <!-- 排序选项按钮 -->
    <div class="sort-btns">
      <div @click="sort('all')" class="sort-item">综合</div>
      <div @click="sort('sales')" class="sort-item">销量</div>
      <div @click="sortPrice" class="sort-item">价格
        <van-icon v-if="price === 1" name="ascending" />
        <van-icon v-else-if="price === 0"  name="descending" />
      </div>
    </div>

    <div class="goods-list">
      <GoodsItem v-for="item in item" :key="item.goods_id" :item="item"></GoodsItem>
    </div>
  </div>
</template>

<script>
import GoodsItem from '@/components/GoodsItem.vue'
import { getProList } from '@/api/product'

export default {
  name: 'SearchIndex',
  components: {
    GoodsItem
  },
  data () {
    return {
      price: 0,
      show: false,
      page: 1,
      item: []
    }
  },
  computed: {
    // 获取地址栏的关键字
    querySearch () {
      return this.$route.query.search
    },
    querycategoryId () {
      return this.$route.query.categoryId
    }
  },
  async created () {
    const res = await getProList({
      categoryId: this.querycategoryId,
      goodsName: this.querySearch,
      page: this.page
    })
    // console.log(res.data.list)
    this.item = res.data.list.data
    // console.log(this.item)
  },
  methods: {
    sortPrice () {
      if (this.price === 0) {
        this.price = 1
      } else if (this.price === 1) {
        this.price = 0
      }
      this.sort('price')
    },
    async sort (str) {
      const res = await getProList({
        sortPrice: this.price,
        sortType: str,
        goodsName: this.querySearch,
        page: this.page
      })
      this.item = res.data.list.data
    },
    showPopup () {
      this.show = true
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  padding-top: 46px;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .tool {
    font-size: 24px;
    height: 40px;
    line-height: 40px;
  }

  .sort-btns {
    display: flex;
    height: 36px;
    line-height: 36px;
    .sort-item {
      text-align: center;
      flex: 1;
      font-size: 16px;
    }
  }
}
// 商品样式
.goods-list {
  background-color: #f6f6f6;
}
</style>
